#include "KeyboardMouseInput.h"

/**********************************
			   MOUSE
***********************************/
void Mouse::Init(HWND& hWnd, HINSTANCE& hInst)
{
	GetCursorPos(&p); // get the window's cursor

	DirectInput8Create(	hInst, 
						DIRECTINPUT_VERSION, 
						IID_IDirectInput8, 
						(void**)&dObj, 
						NULL); 	
	dObj->CreateDevice(GUID_SysMouse, &dIn, NULL);
	dIn->SetDataFormat(&c_dfDIMouse);
	dIn->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);

	ga.Create("Images/TargetCursor16x16.png",		// Cursor image		  
			  D3DXVECTOR3(p.x, p.y, 0.0f),			// Position, windows cursor set here
			  D3DXVECTOR3(1.0f, 1.0f, 0.0f),		// Size
			  0.0f);								// Angle

	tempValue = ga.getPos();						// Retreive position of image
}

void Mouse::Update()
{	
	hr = dIn->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&mouseState);

	if(FAILED(hr))
	{
		hr = dIn->Acquire();			// Find a plugged in keyboard

		while(hr == DIERR_INPUTLOST)	// if not plugged in keep trying until find
			hr = dIn->Acquire();

		if(FAILED(hr))					// if failed for other reason
			return;						// exit

		// Read the state again
		dIn->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&mouseState);
	}
	
	if(GetCursorPos(&p)) {
		ga.setPos(D3DXVECTOR3(p.x, p.y, 0.0f));
	}
}

void Mouse::Render()
{
	//ga.Draw();					// Renders the MOUSE's GameArt
}

void Mouse::Release()
{
	ga.Shutdown();				// Safely RELEASE GameArt's sprite and texture
	dIn->Unacquire();			// Let go of any plug in mouse
	SAFE_RELEASE(dIn);			// Safely RELEASE the device OBJECT
	SAFE_RELEASE(dObj);			// Safely RELEASE the device INPUT
}


/********************************
			KEYBOARD
*********************************/
void Keyboard::Init(HWND& hWnd, HINSTANCE& hInst)
{
	DirectInput8Create(	hInst, 
		DIRECTINPUT_VERSION, 
		IID_IDirectInput8, 
		(void**)&dObj, 
		NULL); 	
	dObj->CreateDevice(GUID_SysKeyboard, &dIn, NULL);
	
	dIn->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	dIn->SetDataFormat(&c_dfDIKeyboard);
	//ga.Create("Images/FlameCircle64x64.png",		// File name			  
	//		  D3DXVECTOR3(200.0f, 200.0f, 0.0f),	// Position
	//		  D3DXVECTOR3(1.0f, 1.0f, 0.0f),		// Size
	//		  0.0f);								// Angle

	//tempValue = ga.getPos();						// Retreive the position of image
}
void Keyboard::Update()
{
	ZeroMemory(buffer, sizeof(buffer));				// clear out buffer
	dIn->Acquire();

	hr = dIn->GetDeviceState(sizeof(buffer), (LPVOID)&buffer);

	if(FAILED(hr))
	{
		hr = dIn->Acquire();						// Find a plugged in keyboard

		while(hr == DIERR_INPUTLOST)				// if not plugged in keep trying until find
			hr = dIn->Acquire();

		if(FAILED(hr))								// if failed for other reason
			return;									// exit

		// Read the state again
		dIn->GetDeviceState(sizeof(buffer), buffer); 
	}
}
void Keyboard::Release()
{
	dIn->Unacquire();
	SAFE_RELEASE(dIn);
	SAFE_RELEASE(dObj);	
}
